import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KeyValueStoreImpl extends UnicastRemoteObject implements KeyValueStore {
//    private Map<String, Node> nodes;
    private ConsistentHash<Node> consistentHash;
    private int numberOfReplicas=100;
    private List<String> keyList = new ArrayList<>();
    private List<String> valueList = new ArrayList<>();
    public KeyValueStoreImpl(String nodeIds) throws RemoteException {
        super();
        this.consistentHash = new ConsistentHash<>(nodeIds);//这一步直接改成new Node，可以删掉consistentHash了，然后下面的new node都可以删掉了
    }
    @Override
    public void put(String key, String value) throws RemoteException {
        Node node = consistentHash.get(key);//可删
        node.getData().put(key, value);
        System.out.println("键值对 " + key + "-" + value + " 存放到了名为 " + node.getNodeId() + " 的服务器节点" );
    }

    @Override
    public String get(String key) throws RemoteException {
        Node node = consistentHash.get(key);//可删
        String value = node.getData().get(key);
        System.out.println("键 " + key + " 的值被放在了名为 " + node.getNodeId() + " 的服务器节点 ");
        return value;
    }
    @Override
    public List<String> getNodesKey(String nodeId) throws RemoteException {
    	// 根据nodeId获得它负责的key全体
    	// 清空 keyList
    	keyList.clear();
    	for (int i = 0; i < numberOfReplicas; i++) {
            String virtualNodeId = nodeId + "#" + i;
            Node node = consistentHash.getNode(virtualNodeId);
            String[] Arraykeys = node.getKey(nodeId);
            for(String keys : Arraykeys) {
            	keyList.add(keys);
            }
        }
    	
    	return keyList;
    }
    @Override
    public List<String> getNodesValue(String nodeId) throws RemoteException {
    	// 清空 valueList
    	valueList.clear();
    	// 根据nodeId获得它负责的value全体
    	for (int i = 0; i < numberOfReplicas; i++) {
            String virtualNodeId = nodeId + "#" + i;
            Node node = consistentHash.getNode(virtualNodeId);
            String[] Arrayvalues = node.getValue(nodeId);
            for(String values : Arrayvalues) {
            	valueList.add(values);
            }
        }
//    	public List<String> removeNodesValue(String nodeId)
    	return valueList;
    }
    @Override
    public void removeKey(String key) throws RemoteException {
    	Node node = consistentHash.get(key);////可删
        node.getData().remove(key);
        System.out.println("键值为 " + key + " 的键值对被转存到另外一个服务器节点上了" );
    }
}
